package com.shitou.springai1.user.service;

import com.shitou.springai1.user.entity.ConversationMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// ConversationMemoryService.java
@Service
@Slf4j
public class ConversationMemoryService {

    // 内存存储对话记录（生产环境建议使用Redis）
    private final Map<String, ConversationMemory> conversationMemories = new ConcurrentHashMap<>();
    private final int DEFAULT_MAX_TURNS = 20; // 默认保存最近20轮对话
    private final long SESSION_TIMEOUT_MINUTES = 30; // 会话超时时间

    /**
     * 获取或创建会话记忆
     */
    public ConversationMemory getOrCreateMemory(String sessionId) {
        return getOrCreateMemory(sessionId, DEFAULT_MAX_TURNS);
    }

    public ConversationMemory getOrCreateMemory(String sessionId, int maxTurns) {
        // 清理过期会话
        cleanupExpiredSessions();

        return conversationMemories.computeIfAbsent(sessionId,
            id -> new ConversationMemory(id, maxTurns));
    }

    /**
     * 添加对话轮次
     */
    public void addConversationTurn(String sessionId, String role, String content) {
        ConversationMemory memory = getOrCreateMemory(sessionId);
        memory.addTurn(role, content);
        log.debug("为会话 {} 添加{}对话记录，当前共{}轮",
                 sessionId, role, memory.getHistory().size());
    }

    /**
     * 获取对话历史摘要
     */
    public String getConversationSummary(String sessionId) {
        ConversationMemory memory = conversationMemories.get(sessionId);
        if (memory == null || memory.getHistory().isEmpty()) {
            return "";
        }

        return memory.getFormattedHistory();
    }

    /**
     * 清理过期会话
     */
    @Scheduled(fixedRate = 300000) // 每5分钟清理一次
    public void cleanupExpiredSessions() {
        LocalDateTime cutoff = LocalDateTime.now().minusMinutes(SESSION_TIMEOUT_MINUTES);
        int initialSize = conversationMemories.size();

        conversationMemories.entrySet().removeIf(entry ->
            entry.getValue().getLastAccessed().isBefore(cutoff));

        int removed = initialSize - conversationMemories.size();
        if (removed > 0) {
            log.info("清理了 {} 个过期会话", removed);
        }
    }

    /**
     * 获取会话统计信息
     */
    public Map<String, Object> getMemoryStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalSessions", conversationMemories.size());
        stats.put("averageTurns", conversationMemories.values().stream()
                .mapToInt(m -> m.getHistory().size())
                .average()
                .orElse(0.0));
        return stats;
    }
}
